<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use app\common\Attribute;
use think\facade\View;
use app\model\Attachment;

#[Attribute(title: "附件管理")]
class AttachmentController extends BaseController
{
    #[Attribute(isAuth: true, isPage: true, title: "查询")]
    public function query()
    {
        if (request()->isPost()) {
            $all = request()->param();
            $data = Attachment::paginate([
                "page" => $all["page"],
                "list_rows" => $all["limit"]
            ]);
            return json([
                "code" => 0,
                "msg" => "获取成功",
                "count" => $data->toArray()["total"],
                "data" => $data->toArray()["data"],
            ]);
        }
        return View::fetch();
    }

    #[Attribute(isAuth: true, isPage: true, title: "添加")]
    public function add()
    {
        return View::fetch();
    }

    #[Attribute(isAuth: true, isPage: false, title: "编辑")]
    public function edit()
    {
        if (request()->isGet()) {
            $id = request()->get('id');
            $find = Attachment::find($id);
            View::assign('find', $find);
        }
        if (request()->isPost()) {
            $all = request()->param();
            try {
                validate(\app\admin\validate\AttachmentValidate::class)
                    ->scene("edit")
                    ->check($all);
                $res = Attachment::update($all);
                if ($res) {
                    return success("操作成功");
                } else {
                    return error("操作失败");
                }
            } catch (\think\exception\ValidateException $e) {
                return error(msg: "验证失败", data: $e->getError());
            }
        }
        return View::fetch();
    }

    #[Attribute(isAuth: true, isPage: false, title: "删除")]
    public function del()
    {
        if (request()->isDelete()) {
            $all = request()->param();
            $url  = Attachment::where('id', $all['id'])->value('url');
            if ($url && file_exists(public_path() . $url)) {
                unlink(public_path() . $url);
            }
            $res = Attachment::destroy($all['id']);
            if ($res) {
                return success("操作成功");
            } else {
                return error("操作失败");
            }
        }
    }
}
